from fastapi import Request
from pydantic import BaseModel
from tortoise.transactions import atomic, in_transaction

from service import RepositoryService, UserService, CollaboratorService, BookService
from common.result.Result import Result
from common.enum import BaseEnum
from common.const import BaseConstant
from util.str import Str
from util.log import Log
from util.token import Token
from util.time import Time
from util.redis import Redis

class Body:
    shortUri: str

async def RecoverRecycleBook(req: Request, body: dict):
    try:
        async with in_transaction() as connection:
            shortUri = body.get('shortUri')
            if Str.isBlank(str(shortUri)):
                return Result.error(BaseEnum.PARAMETER_INVALID_ERROR)

            token = req.headers.get("token")
            user = await UserService.getUserByToken(token)
            if user == None:
                return Result.error(BaseEnum.USER_NOT_EXISTS_ERROR)
            
            book = await BookService.getRecycleBookByShortUri(shortUri)
            if book == None:
                return Result.error(BaseEnum.BOOK_NOT_EXISTS_ERROR)
            
            repositoryId = book.repository_id
            repository = await RepositoryService.getRepositoryById(repositoryId)
            if repository == None:
                return Result.error(BaseEnum.REPOSITORY_NOT_EXISTS_ERROR)
            
            # 判断仓库是否允许用户写（只能 协作者 和 创建者 写）
            flag = await RepositoryService.getUserWritePermission(repository, user.id)
            if flag == False:
                return Result.error(BaseEnum.REPOSITORY_NO_WRITE_PERMISSION_ERROR)

            res = await BookService.recoverRecycleBook(book.short_uri)
        
            # 删除 book tree 的缓存
            key = BaseConstant.BOOK_TREE_KEY % repository.short_uri
            Redis.deleteItem(key)

            return Result.success(res)
    except Exception as e:
        Log.error('从回收站恢复 book 异常', e)
        return Result.error(BaseEnum.SERVICE_ERROR)
